package com.jt.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.internal.runtime.PropertyAccess;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.net.UnknownHostException;

/**
 * 在配置类自定义RedisTemplate的配置
 */
@Configuration
public class RedisConfig {

    //方案二： 高级定制(改变)
    public RedisSerializer<Object> jsonSerializer(){
        //1.定义JSON序列化，反序列化的对象
        Jackson2JsonRedisSerializer<Object> jsonSerializer =
                new Jackson2JsonRedisSerializer<Object>(Object.class);
        //2.定义序列化规则
        //2.定义序列化规则(序列化规则由ObjectMapper定义)
        //2.1创建ObjectMapper对象
        ObjectMapper objectMapper = new ObjectMapper();
        //2.2指定按什么规则进行序列化
        //2.2.1按什么方法进行序列化(任意访问修饰符的get方法)
        objectMapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.ANY);
        //2.2.2假如属性值为null则不再进行此属性的序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //2.2.3将对象类型写入到序列化的字符串中
//        objectMapper.activateDefaultTyping(
//                objectMapper.getPolymorphicTypeValidator(),//多态校验
//                ObjectMapper.DefaultTyping.NON_FINAL,//非final对象允许序列化
//                JsonTypeInfo.As.PROPERTY);//类型以属性形式存储

        return null;
    }


    //方案一
    //RedisTemplate简单定制的实现
    @Bean                                             //连接工厂
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        //修改默认的序列化方式(默认为JDK的序列化方式)
        //设置key的序列化的方式
        template.setKeySerializer(RedisSerializer.string());//大key
        //小key(value为hash类型时)
        template.setHashKeySerializer(RedisSerializer.string());
        //设置值的序列化方式
//        template.setValueSerializer(RedisSerializer.json());
//        template.setHashValueSerializer(RedisSerializer.json());
        template.setValueSerializer(jsonSerializer());
        template.setHashValueSerializer(jsonSerializer());

        return template;
    }
}
